package com.aluvfy.jdbc;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ResourceBundle;
//以特定的类型取出数据
public class JDBCTest04 {
    public static void main(String[] args) {
        //读取属性配置文件，读取数据库连接
        ResourceBundle bundle = ResourceBundle.getBundle("com.aluvfy.jdbc.jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stm = null;
        ResultSet rs = null;

        //ctrl alt t 异常处理
        try {
            //1. 注册驱动
            Class.forName(driver);
            //2. 获取连接
            conn = DriverManager.getConnection(url, user, password);
            //3. 获取数据库操作对象
            stm = conn.createStatement();
            //4. 执行sql语句
            String sql = "select id, name, price, create_time from t_product";
            rs = stm.executeQuery(sql);
            //5. 处理查询结果集
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            while (rs.next()) {
                //以特定的类型取出数据
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                //注意：这里返回的Date类型是java.sql.Date类型，不是Java.util.Date类型
                Date createTime = rs.getDate("create_time");
                System.out.println(id + "\t" + name + "\t" + price + "\t" + createTime);

                //将java.sql.Date类型转换为java.util.Date类型(调用构造方法来实现)
                java.util.Date date = new java.util.Date(createTime.getTime());
                //进行格式化显示
                String strDate = sdf.format(date);
                System.out.println(strDate);
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //6. 关闭资源
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (stm != null) stm.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }




    }
}
